package com.share.dymamic.utils;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class EncryptUtils{
	private static String DEFAULT_ENCRYPT_KEY = "s0h2OZqES6d8Dd3S9LVD8Q==";
	public static final String KEY_ALGORITHM = "AES";
	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	public static String initkey()throws Exception{
	    KeyGenerator kg = KeyGenerator.getInstance("AES");
	    kg.init(128);
	    SecretKey secretKey = kg.generateKey();
	    return Base64.encodeBase64String(secretKey.getEncoded());
	}
	
	public static Key toKey(byte[] key)throws Exception{
	    return new SecretKeySpec(key, "AES");
	}
	
	public static String encrypt(String data, String key)throws Exception{
	    Key k = toKey(Base64.decodeBase64(key));
	    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	    cipher.init(1, k);
	    return Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
	}
	
	public static String encrypt(String data) throws Exception {
	    Key k = toKey(Base64.decodeBase64(DEFAULT_ENCRYPT_KEY));
	    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	    cipher.init(1, k);
	    return Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
	}
	
	public static String decrypt(String data, String key)throws Exception{
	    Key k = toKey(Base64.decodeBase64(key));
	    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	    cipher.init(2, k);
	    return new String(cipher.doFinal(Base64.decodeBase64(data)));
	}
	
	public static String decrypt(String data) throws Exception{
	    Key k = toKey(Base64.decodeBase64(DEFAULT_ENCRYPT_KEY));
	    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	    cipher.init(2, k);
	    return new String(cipher.doFinal(Base64.decodeBase64(data)));
	}
	
	public static void main(String[] args) throws Exception{
	    String source = "123";
	
	    System.out.println("原文：" + source);
	
	    String key = initkey();
	    System.out.println("密钥：" + key);
	
	    String encryptData = encrypt(source, key);
	    System.out.println("加密：" + encryptData);
	
	    String decryptData = decrypt(encryptData, key);
	    System.out.println("解密: " + decryptData);
	}
}